import 'dart:math';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'stu_sign.dart';
import 'tea_sign.dart';
import 'register.dart';
import 'forget_password.dart';
import 'constants.dart';

bool isJwtExpired(String jwt) {
  // 解码JWT
  List<String> parts = jwt.split('.');
  String payload = parts[1];
  String decodedPayload =
      utf8.decode(base64Url.decode(base64Url.normalize(payload)));
  print(decodedPayload);
  // 将解码后的 JSON 转换为 Dart Map
  Map<String, dynamic> payloadMap = json.decode(decodedPayload);

  // 获取过期时间（exp）并转换为 DateTime
  int expTimestamp = payloadMap['exp'];
  DateTime expirationTime =
      DateTime.fromMillisecondsSinceEpoch(expTimestamp * 1000);

  // 获取当前时间
  DateTime currentTime = DateTime.now();

  // 检查是否过期
  return expirationTime.isBefore(currentTime);
}

Future<void> storeJwtToken(String type, String token) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setString(type, token);
}

Future<String> retrieveJwtToken(String type) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();

  // 从存储中检索数据
  String jwt = prefs.getString(type) ?? ''; // 使用空字符串作为默认值

  return jwt;
}

void main() {
  WidgetsFlutterBinding.ensureInitialized(); // 确保 Flutter 绑定已初始化

  retrieveJwtToken("access_token").then((jwt) {
    if (jwt.isNotEmpty && !isJwtExpired(jwt) && false) {
      // 如果access_token不为空且未过期，则跳转到主屏幕
      retrieveJwtToken("role").then((role) {
        if (role == "Student") {
          runApp(stu_comsic());
        } else if (role == "Teacher") {
          runApp(tea_comsic());
        } else {
          print("unknown role");
        }
      });
    } else {
      // 否则，跳转到登录屏幕
      runApp(Login());
    }
  });
}

class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CenteredText(),
    );
  }
}

class CenteredText extends StatefulWidget {
  @override
  _CenteredTextState createState() => _CenteredTextState();
}

class _CenteredTextState extends State<CenteredText> {
  TextEditingController phoneController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  bool _obscureText = true;
  bool isChecked = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Expanded(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              // const SizedBox(height: 100.0),
              const Text(
                '宇签',
                style: TextStyle(
                  fontFamily: 'Raleway',
                  fontSize: 42,
                  fontWeight: FontWeight.w900,
                  color: Color.fromARGB(255, 179, 202, 193),
                ),
              ),
              const Text(
                '记录我的课程生活',
                style: TextStyle(
                  fontSize: 12,
                ),
              ),
              const SizedBox(height: 50.0),
              HighlightButtons(),
              const SizedBox(height: 20.0),
              buildTextField(phoneController, '请输入手机号'),
              SizedBox(height: 10.0),
              buildPasswordTextField(passwordController, '请输入密码'),
              SizedBox(height: 20.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  buildWhiteElevatedButton('注册', register),
                  buildElevatedButton('登录', login),
                ],
              ),

              SizedBox(height: 20.0),
              Row(
                children: [
                  roundCheckbox(isChecked, (value) {
                    setState(() {
                      isChecked = value!;
                    });
                  }),
                  Text(
                    '已阅读并同意隐私协议',
                    style: TextStyle(fontSize: 15),
                  ),
                  SizedBox(width: 100.0),
                  UnderlineButton(
                    text: '忘记密码',
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => ForgotPasswordPage()),
                      );
                      // 按钮按下时执行的操作
                      print('Button Clicked');
                    },
                  ),
                ],
              ),
              // SizedBox(height: 10.0),
              IconButtonsWidget(),
            ],
          ),
        ),
      ),
    );
  }

  Widget roundCheckbox(bool isChecked, ValueChanged<bool?> onChanged) {
    return Checkbox(
      checkColor: Colors.white,
      fillColor: MaterialStateProperty.resolveWith((states) {
        const Set<MaterialState> interactiveStates = <MaterialState>{
          MaterialState.pressed,
          MaterialState.hovered,
          MaterialState.focused,
        };
        if (states.any(interactiveStates.contains)) {
          return Colors.blue; // 选中时的颜色
        }
        return Color.fromARGB(255, 179, 202, 193); // 未选中时的颜色
      }),
      value: isChecked,
      shape: CircleBorder(),
      onChanged: onChanged,
    );
  }

  Widget buildTextField(TextEditingController controller, String hintText) {
    double screenWidth =
        MediaQuery.of(context).size.width; // Get the screen width
    double containerWidth = screenWidth *
        0.65; // Set the container width to 80% of the screen width

    return Container(
      width: containerWidth,
      padding: EdgeInsets.symmetric(horizontal: 20.0),
      decoration: BoxDecoration(
        border: Border.all(color: Color.fromARGB(255, 179, 202, 193)),
        borderRadius: BorderRadius.circular(10.0),
        color: Color.fromARGB(255, 244, 248, 245),
      ),
      child: TextField(
        controller: controller,
        decoration: InputDecoration(
          hintText: hintText,
          border: InputBorder.none,
        ),
      ),
    );
  }

  Widget buildPasswordTextField(
      TextEditingController controller, String hintText) {
    double screenWidth =
        MediaQuery.of(context).size.width; // Get the screen width
    double containerWidth = screenWidth *
        0.65; // Set the container width to 80% of the screen width
    return Container(
      width: containerWidth,
      padding: EdgeInsets.symmetric(horizontal: 20.0),
      decoration: BoxDecoration(
        border: Border.all(color: Color.fromARGB(255, 179, 202, 193)),
        borderRadius: BorderRadius.circular(10.0),
        color: Color.fromARGB(255, 244, 248, 245),
      ),
      child: TextField(
        controller: controller,
        decoration: InputDecoration(
          hintText: hintText,
          border: InputBorder.none,
          suffixIcon: GestureDetector(
            onTap: () {
              setState(() {
                _obscureText = !_obscureText;
              });
            },
            child: Icon(
              _obscureText ? Icons.visibility : Icons.visibility_off,
            ),
          ),
        ),
        obscureText: _obscureText,
      ),
    );
  }

  Widget buildElevatedButton(String label, Function() onPressed) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(label, style: TextStyle(fontSize: 14)),
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.all<Color>(
            Color.fromARGB(255, 179, 202, 193)), // Set the background color
        minimumSize: MaterialStateProperty.all<Size>(
            Size(120, 40)), // Set the minimum size
      ),
    );
  }

  Widget buildWhiteElevatedButton(String label, Function() onPressed) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(label, style: TextStyle(fontSize: 14, color: Colors.black)),
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.all<Color>(
            Color.fromARGB(255, 238, 239, 239)), // Set the background color
        minimumSize: MaterialStateProperty.all<Size>(
            Size(120, 40)), // Set the minimum size
      ),
    );
  }

  Future<void> register() async {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => RegistrationPage()),
    );
  }

  Future<void> login() async {
    const String serverUrl = AppConstants.serverUrl;
    var url = Uri.parse('$serverUrl/v1/login'); // API URL

    Map<String, String> body = {
      'phone': phoneController.text,
      'password': passwordController.text,
    };

    try {
      var response = await http.post(
        url,
        headers: {'Content-Type': 'application/json'},
        body: json.encode(body),
      );

      _handleLoginResponse(response);
    } catch (e) {
      showErrorDialog('登录错误', '无法连接到服务器，请检查您的网络连接');
    }
  }

  void _handleLoginResponse(http.Response response) {
    if (response.statusCode == 200) {
      _processSuccessfulLogin(response.body);
    } else {
      _processFailedLogin(response.body, response.statusCode);
    }
  }

  void _processSuccessfulLogin(String responseBody) {
    var responseData = json.decode(responseBody);
    String access_token = responseData['access_token'];
    String refresh_token = responseData['refresh_token'];
    String role = responseData['role'];

    storeJwtToken("access_token", access_token);
    storeJwtToken("refresh_token", refresh_token);
    storeJwtToken("role", role);

    _navigateBasedOnRole(role);
  }

  void _processFailedLogin(String responseBody, int statusCode) {
    final Map<String, dynamic> responseData = json.decode(responseBody);
    final int errorCode = responseData['errorcode'];

    switch (errorCode) {
      case 40001:
        showErrorDialog('登录失败', '无效的json格式');
        break;
      case 40002:
        showErrorDialog('登录失败', '无效的手机号');
        break;
      case 40006:
        showErrorDialog('登录失败', '此用户不存在');
        break;
      case 40007:
        showErrorDialog('登录失败', '密码错误');
        break;
      default:
        showErrorDialog('登录失败', '发生未知错误');
    }
  }

  void _navigateBasedOnRole(String role) {
    if (role == "Student") {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => stu_comsic()),
      );
    } else if (role == "Teacher") {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => tea_comsic()),
      );
    } else {
      print("unknown role");
    }
  }

  void showErrorDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return buildAlertDialog(title, content);
      },
    );
  }

  void showSuccessDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return buildAlertDialog(title, content);
      },
    );
  }

  AlertDialog buildAlertDialog(String title, String content) {
    return AlertDialog(
      title: Text(title),
      content: Text(content),
      actions: [
        TextButton(
          child: Text('确定'),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }
}

class HighlightButtons extends StatefulWidget {
  final _HighlightButtonsState state = _HighlightButtonsState();

  @override
  _HighlightButtonsState createState() => state;

  String getRole() {
    return state.isButton1Highlighted ? "Student" : "Teacher";
  }
}

class _HighlightButtonsState extends State<HighlightButtons> {
  bool isButton1Highlighted = true; // Button 1 is initially highlighted
  bool isButton2Highlighted = false;

  void _highlightButton1() {
    setState(() {
      isButton1Highlighted = true;
      isButton2Highlighted = false; // Unhighlight Button 2
    });
  }

  void _highlightButton2() {
    setState(() {
      isButton2Highlighted = true;
      isButton1Highlighted = false; // Unhighlight Button 1
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center, // Center the buttons
      children: [
        GestureDetector(
          onTap: _highlightButton1,
          child: Container(
            padding: EdgeInsets.all(16.0),
            decoration: BoxDecoration(
              color: isButton1Highlighted
                  ? Color.fromARGB(255, 179, 202, 193)
                  : Color.fromARGB(255, 244, 248, 245),
              borderRadius: BorderRadius.circular(10.0), // Add rounded corners
            ),
            child: Text(
              '我是学生',
              style: TextStyle(
                fontSize: 18,
              ),
            ),
          ),
        ),
        GestureDetector(
          onTap: _highlightButton2,
          child: Container(
            padding: EdgeInsets.all(16.0),
            decoration: BoxDecoration(
              color: isButton2Highlighted
                  ? Color.fromARGB(255, 179, 202, 193)
                  : Color.fromARGB(255, 244, 248, 245),
              borderRadius: BorderRadius.circular(10.0), // Add rounded corners
            ),
            child: Text(
              '我是老师',
              style: TextStyle(
                fontSize: 18,
              ),
            ),
          ),
        ),
      ],
    );
  }
}

class UnderlineButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;

  const UnderlineButton({
    required this.text,
    required this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPressed,
      child: Text(
        text,
        style: const TextStyle(
          decoration: TextDecoration.underline,
          color: Colors.black, // 可以更改颜色
          fontSize: 15.0, // 可以更改字体大小
          // fontWeight: FontWeight.bold, // 可以更改字体粗细
        ),
      ),
    );
  }
}

class IconButtonsWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        IconButton(
          icon: Image.asset('images/icon_QQ.png'), // 第一个按钮，使用 QQ 图标
          onPressed: () {
            // 点击按钮时的操作
            print('QQ Icon Button Clicked');
          },
          iconSize: 30, // 图标大小
          color: Colors.blue, // 图标颜色
        ),
        SizedBox(width: 20), // 添加一些垂直间距
        IconButton(
          icon: Image.asset('images/icon_WeChat.png'), // 第二个按钮，使用微信图标
          onPressed: () {
            // 点击按钮时的操作
            print('WeChat Icon Button Clicked');
          },
          iconSize: 30, // 图标大小
          color: Colors.green, // 图标颜色
        ),
      ],
    );
  }
}
